package com.lifeonwalden.game.mindustry.entity;

import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.lifeonwalden.game.mindustry.Global;
import com.lifeonwalden.game.mindustry.constant.BulletType;
import com.lifeonwalden.game.mindustry.constant.League;
import com.lifeonwalden.game.mindustry.constant.ResourceType;
import com.lifeonwalden.game.mindustry.feature.TextureUnit;

public class Bullet implements TextureUnit {
    public BulletType type;
    public float startX;
    public float startY;
    public float x;
    public float y;
    public double cosA = 0;
    public double sinA = 0;
    public boolean runOut = false;
    public boolean hit = false;
    public League from;
    private long startTime;

    public Bullet(League from, BulletType type, float startX, float startY, float targetX, float targetY) {
        this.from = from;
        this.type = type;
        if (startX == targetX) {
            sinA = 1;
        } else if (startY == targetY) {
            cosA = 1;
        } else {
            double a = Math.abs(targetX - startX), b = Math.abs(targetY - startY);
            double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
            sinA = b / c;
            cosA = a / c;
        }

        if (targetX < startX) {
            cosA *= -1;
        }

        if (targetY < startY) {
            sinA *= -1;
        }

        this.startX = startX;
        this.startY = startY;
        this.startTime = System.currentTimeMillis();
    }

    public void doJobBefore() {
        long lifeTime = System.currentTimeMillis() - startTime;
        if (lifeTime > this.type.lifetime) {
            this.runOut = true;
        } else {
            double distance = lifeTime * this.type.speed;
            this.x = (float) (startX + this.cosA * distance);
            this.y = (float) (startY + this.sinA * distance);

            if (Global.world.fight(this)) {
                this.hit = true;
            }
        }
    }

    @Override
    public void draw(Batch batch) {
        if (!runOut) {
            if (this.hit) {
                batch.draw(ResourceType.Iron.texture, this.x - 4, this.y - 4);
            } else {
                batch.draw(this.type.texture, this.x - 4, this.y - 4);
            }
        }
    }

    @Override
    public void doJobAfter() {
        if (hit) {
            runOut = true;
        }
    }

    @Override
    public TextureRegion texture() {
        return this.type.texture;
    }

    @Override
    public short x() {
        return (short) this.x;
    }

    @Override
    public void x(short x) {
        this.x = x;
    }

    @Override
    public short y() {
        return (short) this.y;
    }

    @Override
    public void y(short y) {
        this.y = y;
    }
}
